<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="第3章：函数作用域和块级作用域3.1 函数中的作用域  JavaScript变量的查找规则是由内到外的 ，阅读如下代码：12345678910function foo(a)&amp;#123;    var b &#x3D; 2;    function bar()&amp;#123;        &#x2F;&#x2F;...    &amp;#125;    var c &#x3D; 3;&amp;#125;bar();  &#x2F;&#x2F;失败console.log(a,b">
<meta property="og:type" content="article">
<meta property="og:title" content="《你不知道的JavaScript(上)》S01E03">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E03/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="第3章：函数作用域和块级作用域3.1 函数中的作用域  JavaScript变量的查找规则是由内到外的 ，阅读如下代码：12345678910function foo(a)&amp;#123;    var b &#x3D; 2;    function bar()&amp;#123;        &#x2F;&#x2F;...    &amp;#125;    var c &#x3D; 3;&amp;#125;bar();  &#x2F;&#x2F;失败console.log(a,b">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-11-29T14:14:17.000Z">
<meta property="article:modified_time" content="2020-12-01T15:07:28.562Z">
<meta property="article:author" content="William Leung">
<meta property="article:tag" content="你不知道的JavaScript">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E03/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>《你不知道的JavaScript(上)》S01E03 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC3%E7%AB%A0%EF%BC%9A%E5%87%BD%E6%95%B0%E4%BD%9C%E7%94%A8%E5%9F%9F%E5%92%8C%E5%9D%97%E7%BA%A7%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">1.</span> <span class="nav-text">第3章：函数作用域和块级作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-%E5%87%BD%E6%95%B0%E4%B8%AD%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">1.1.</span> <span class="nav-text">3.1 函数中的作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-%E9%9A%90%E8%97%8F%E5%86%85%E9%83%A8%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.2.</span> <span class="nav-text">3.2 隐藏内部实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E5%85%A8%E5%B1%80%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">(1) 全局命名空间</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E6%A8%A1%E5%9D%97%E7%AE%A1%E7%90%86"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">(2) 模块管理</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-%E5%87%BD%E6%95%B0%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">1.3.</span> <span class="nav-text">3.3 函数作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-%E5%9D%97%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">1.4.</span> <span class="nav-text">3.3 块作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#with"><span class="nav-number">1.4.0.1.</span> <span class="nav-text">with</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#try-catch"><span class="nav-number">1.4.0.2.</span> <span class="nav-text">try&#x2F;catch</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#let"><span class="nav-number">1.4.0.3.</span> <span class="nav-text">let</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#const"><span class="nav-number">1.4.0.4.</span> <span class="nav-text">const</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-5-%E5%B0%8F%E7%BB%93"><span class="nav-number">1.5.</span> <span class="nav-text">3.5 小结</span></a></li></ol></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E03/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《你不知道的JavaScript(上)》S01E03
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-11-29 22:14:17" itemprop="dateCreated datePublished" datetime="2020-11-29T22:14:17+08:00">2020-11-29</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2020-12-01 23:07:28" itemprop="dateModified" datetime="2020-12-01T23:07:28+08:00">2020-12-01</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>3.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>3 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第3章：函数作用域和块级作用域"><a href="#第3章：函数作用域和块级作用域" class="headerlink" title="第3章：函数作用域和块级作用域"></a>第3章：函数作用域和块级作用域</h1><h2 id="3-1-函数中的作用域"><a href="#3-1-函数中的作用域" class="headerlink" title="3.1 函数中的作用域"></a>3.1 函数中的作用域</h2><ul>
<li> <strong>JavaScript变量的查找规则是由内到外的</strong> ，阅读如下代码：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">//...</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> c = <span class="number">3</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">bar();  <span class="comment">//失败</span></span><br><span class="line"><span class="built_in">console</span>.log(a,b,c); <span class="comment">//失败</span></span><br></pre></td></tr></table></figure></li>
<li><code>foo()</code>函数作用域声明了变量<code>a</code>、<code>b</code>、<code>c</code>以及函数<code>bar</code>，如果在外部使用这些函数内的变量或函数都会失败。</li>
<li> <strong>函数作用域的含义就是说，函数内的变量只允许在函数范围内使用（也包括在内部嵌套函数）。</strong></li>
</ul>
<h2 id="3-2-隐藏内部实现"><a href="#3-2-隐藏内部实现" class="headerlink" title="3.2 隐藏内部实现"></a>3.2 隐藏内部实现</h2><ul>
<li>既然函数中变量的活动范围只限制在函数内，反过来其实也可以这么理解：</li>
<li>我们挑选一个代码片段，用函数作用域将其包装起来了，而 <strong>函数内的具体细节(变量)对外不可见，被“隐藏”起来了。</strong></li>
<li>这种做法就是 <strong>软件设计中的<code>最小授权</code>或<code>最小暴露原则</code></strong> 。</li>
<li>如果所有变量和函数都声明到全局作用域中，可能会发生无法预知的情况：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> b;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    b = a + doSomethingElse(a * <span class="number">2</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(b * <span class="number">3</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomethingElse</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a - <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">doSomething(<span class="number">2</span>); <span class="comment">//15</span></span><br></pre></td></tr></table></figure>
通过函数作用域修改后，是不是更安心了：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> b;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">doSomethingElse</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a - <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    b = a + doSomethingElse(a * <span class="number">2</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(b * <span class="number">3</span>);</span><br><span class="line">&#125;</span><br><span class="line">doSomething(<span class="number">2</span>); <span class="comment">//15</span></span><br></pre></td></tr></table></figure></li>
<li>另外，<strong>通过作用域隐藏变量还有一个好处：可以避免因为同名造成的变量冲突。</strong><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">        i = <span class="number">3</span>;</span><br><span class="line">        <span class="built_in">console</span>.log(a + i);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;<span class="number">10</span>;i++)&#123;</span><br><span class="line">        bar(i * <span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">foo();  <span class="comment">//因为调用的i是通一个，造成无限循环</span></span><br></pre></td></tr></table></figure></li>
<li>针对同名变量冲突，大概有两种处理方式：<h4 id="1-全局命名空间"><a href="#1-全局命名空间" class="headerlink" title="(1) 全局命名空间"></a>(1) 全局命名空间</h4></li>
<li>将本来暴露在全局作用域的诸多变量，统一放到全局的某个对象中，这个对象看做一个命名空间。</li>
<li>jQuery采用的就是此类做法，将所有和jQuery关联的第三方插件，都放到jQuery对象下。</li>
</ul>
<h4 id="2-模块管理"><a href="#2-模块管理" class="headerlink" title="(2) 模块管理"></a>(2) 模块管理</h4><ul>
<li>如同<code>seaJS</code>、<code>requireJS</code>等现代化的模块机制一样</li>
<li>首先将JS第三方库统一注册到模块管理器中，当调用的方法需要某个库时，从模块管理器中将该库挑选出来，显式的注入到函数作用域里。</li>
<li>这样不仅避免了全局作用域的污染，更实现了按需加载。</li>
</ul>
<h2 id="3-3-函数作用域"><a href="#3-3-函数作用域" class="headerlink" title="3.3 函数作用域"></a>3.3 函数作用域</h2><ul>
<li>上文说到，通过函数作用域来隐藏变量能避免一系列的问题，但这并不是最理想的：<ul>
<li>为了隐藏几个变量，我还得声明一个具名函数，那这个函数本身，不也在污染全局作用域吗？</li>
<li>其次，声明了函数还得去调用才能运行起来。</li>
</ul>
</li>
<li>是否有可以 <strong>不用指定函数名，并且还能自动运行的函数</strong> 呢？答案是肯定的：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">(<span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line">&#125;)();</span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//2 函数作用域对内部的a做了隐藏，不影响全局的作用域</span></span><br></pre></td></tr></table></figure></li>
<li><strong>当以<code>()</code>中括号包含函数时，则是函数表达式，而不是标准的函数声明。</strong></li>
<li>不要对函数表达式感到陌生，其实早在定时函数<code>setTimeout()</code>我们就有用到过：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;I waited 1 second!&#x27;</span>);</span><br><span class="line">&#125;,<span class="number">1000</span>);</span><br></pre></td></tr></table></figure></li>
<li>定时函数中用到的叫<code>匿名函数表达式</code>，因为没有指定函数名。</li>
<li>注意， <strong>函数表达式是可以匿名的，但函数声明则不允许匿名。</strong></li>
<li>使用函数表达式需要注意的几点：<ul>
<li>匿名函数不便于调试；</li>
<li>当函数需要引用自身的时候比较困难，只能引用已经过期的<code>arguments.callee</code>；</li>
<li>由于匿名函数缺乏函数名，代码的可读性较差；</li>
</ul>
</li>
<li>用<code>()</code>包含一个函数可以构造一个函数表达式，而 <strong>在末尾紧跟着一个<code>()</code>可以立即执行这个函数</strong> 。</li>
<li>JS社区将它命名为 __<code>IIFE(Immediately Invoked Function Expresion)</code>，代表立即执行的函数表达式__。</li>
<li>IIFE还有另外一种写法：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;test&#x27;</span>);</span><br><span class="line">&#125;())</span><br></pre></td></tr></table></figure></li>
<li><strong>IIFE可以传递参数</strong> ：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"><span class="built_in">global</span></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">global</span>.a);  <span class="comment">//2</span></span><br><span class="line">&#125;)(<span class="built_in">window</span>);</span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//2</span></span><br></pre></td></tr></table></figure></li>
<li><strong>IIFE</strong> 还有一种 <strong>可以倒置代码的运行顺序</strong> 的玩法，这种模式在UMD（Universal Module Definition）项目中运用广泛：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">(<span class="function"><span class="keyword">function</span> <span class="title">iife</span>(<span class="params">def</span>)</span>&#123;</span><br><span class="line">    def(<span class="built_in">window</span>);</span><br><span class="line">&#125;)(<span class="function"><span class="keyword">function</span>(<span class="params"><span class="built_in">global</span></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">global</span>.a);  <span class="comment">//2</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="3-3-块作用域"><a href="#3-3-块作用域" class="headerlink" title="3.3 块作用域"></a>3.3 块作用域</h2><ul>
<li>虽然函数作用域是最常见的作用域，但JavaScript也有其他的作用域单元，甚至在很多场景下，甚至用这些非函数的作用域单元实现功能，代码会更简洁、更优雅。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//虽然i声明于for循环的花括号范围内</span></span><br><span class="line"><span class="comment">//但注意i是用var来声明的，实际上它是全局作用域下的变量</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;<span class="number">10</span>;i++)&#123;</span><br><span class="line">    consooe.log(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><code>for</code>循环中的<code>i</code>经常会由于忽略，会被绑定到全局作用域，而JavaScript的块级作用域就可以将变量限制在花括号的范围内。<h4 id="with"><a href="#with" class="headerlink" title="with"></a>with</h4></li>
<li>前文提到的<code>with</code>就可以构造块级作用域，但不提倡使用。<h4 id="try-catch"><a href="#try-catch" class="headerlink" title="try/catch"></a>try/catch</h4></li>
<li><code>catch</code>分句中，也会创建一个块级作用域。在其中声明的变量仅在<code>catch</code>内部有效。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line">    makeError();</span><br><span class="line">&#125;<span class="keyword">catch</span>(err)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err);</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(err);   <span class="comment">//ReferenceError: err not found</span></span><br></pre></td></tr></table></figure>
<h4 id="let"><a href="#let" class="headerlink" title="let"></a>let</h4></li>
<li>ES6引入了 <strong><code>let</code>关键字，可以将变量绑定到所在代码的作用域中</strong> （通常是花括号<code>&#123;&#125;</code>内）。换句话说，<code>let</code>为其声明的变量隐式的劫持了所在的块作用域。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = <span class="literal">true</span>;</span><br><span class="line"><span class="keyword">if</span>(foo)&#123;</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">let</span> bar = foo * <span class="number">2</span>;</span><br><span class="line">        bar = something(bar);</span><br><span class="line">        <span class="built_in">console</span>.log(bar);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(bar);   <span class="comment">//ReferenceError</span></span><br></pre></td></tr></table></figure></li>
<li>注意：但 <strong><code>let</code>关键字不会进行变量声明的提升</strong> ，请确保代码在运行时已进行声明。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(bar);   <span class="comment">//ReferenceError!</span></span><br><span class="line">    <span class="keyword">let</span> bar = <span class="number">2</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="const"><a href="#const" class="headerlink" title="const"></a>const</h4></li>
<li>ES6中的 __<code>const</code>同样也可以创建块级作用域变量，但变量值是固定的（常量）__。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = <span class="literal">true</span>;</span><br><span class="line"><span class="keyword">if</span>(foo)&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">const</span> b = <span class="number">3</span>;    <span class="comment">//在if块级作用域下的常量</span></span><br><span class="line">    </span><br><span class="line">    a = <span class="number">3</span>;  <span class="comment">//赋值正常</span></span><br><span class="line">    b = <span class="number">4</span>;  <span class="comment">//赋值失败！常量不能改变</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line"><span class="built_in">console</span>.log(b); <span class="comment">//ReferenceError!</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="3-5-小结"><a href="#3-5-小结" class="headerlink" title="3.5 小结"></a>3.5 小结</h2><ul>
<li>函数是JavaScript中最常见的作用域单位，声明在函数内的变量会被函数作用域“隐藏”起来，这是软件设计的最小暴露原则。</li>
<li>函数不是唯一的作用域单位，块级作用域是指变量属于某个代码段（通常拥有花括号<code>&#123;&#125;</code>）下。</li>
<li><code>try/catch</code>的<code>catch</code>分句拥有块作用域。</li>
<li>ES6的<code>let</code>和<code>const</code>关键字能在任意代码段中创建块作用域变量。</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E03/" title="《你不知道的JavaScript(上)》S01E03">https://gitee.com/lianghuilin/murmur.git/reading_notes/《你不知道的JavaScript-上-》S01E03/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/murmur/tags/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript/" rel="tag"># 你不知道的JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E02/" rel="prev" title="《你不知道的JavaScript(上)》S01E02">
                  <i class="fa fa-chevron-left"></i> 《你不知道的JavaScript(上)》S01E02
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E04/" rel="next" title="《你不知道的JavaScript(上)》S01E04">
                  《你不知道的JavaScript(上)》S01E04 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
